package customer.zspt.cn.customer.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import customer.zspt.cn.customer.Adapter.HomeFgVpAdapter;
import customer.zspt.cn.customer.R;
import customer.zspt.cn.customer.Services.ListenerNetWorkChangeService;
import customer.zspt.cn.customer.Widget.TabView;
import customer.zspt.cn.customer.bean.PersonalIDao;
import customer.zspt.cn.customer.bean.ServexDao;
import customer.zspt.cn.customer.bean.SkillListDao;
import customer.zspt.cn.customer.components.contact.contact;
import customer.zspt.cn.customer.components.contact.contact_view;
import customer.zspt.cn.customer.components.group.group_view;
import customer.zspt.cn.customer.components.history.history;
import customer.zspt.cn.customer.components.mine.mine;
import customer.zspt.cn.customer.components.servex.servex_view;
import customer.zspt.cn.customer.constant.constant;
import customer.zspt.cn.customer.utils.ChatRecordSPUtils;
import customer.zspt.cn.customer.utils.Chinese2SpellUtils;
import customer.zspt.cn.customer.utils.GetAllInfoUtils;
import customer.zspt.cn.customer.utils.GetNetWorkUtil;
import customer.zspt.cn.customer.utils.MsgTipUtils;
import customer.zspt.cn.customer.utils.NetUtils;
import customer.zspt.cn.customer.utils.SPUtils;
import customer.zspt.cn.customer.utils.WebScoket;

public class main extends BaseActivity implements View.OnClickListener {
    /*** 刷新tab未读数监听器*/
    private WebScoket.RefatorMainMsgCountListener mRefatorMainMsgCountListener = new WebScoket.RefatorMainMsgCountListener() {
        @Override
        public void OnRefactor() {
        }
    };
    private FragmentManager fm = getSupportFragmentManager();
    private List<Fragment> homeFgList;
    @ViewInject(R.id.content_Vp)
    private ViewPager content_Vp;
    @ViewInject(R.id.tab_ll)
    private LinearLayout tab_ll;
    /**
     * 主界面ViewPager滑动监听器
     */
    ViewPager.OnPageChangeListener mMainVpScrollListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }
        @Override
        public void onPageSelected(int position) {
            ChangeIcon(true, position);
            if (position == 1) {
                contact contact = (contact) homeFgList.get(1);
                contact.setData();
            }
        }
        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };
    @ViewInject(R.id.title_search)//搜索按钮
    private ImageButton title_search;
    @ViewInject(R.id.search)
    private LinearLayout search_layout; //搜索界面
    @ViewInject(R.id.chat)//聊天界面
    private TabView chat;
    @ViewInject(R.id.adress)//通讯录界面
    private TabView adress;
    @ViewInject(R.id.me)//我的界面
    private TabView me;
    @ViewInject(R.id.back) //搜索界面返回主界面
    private TextView back;
    @ViewInject(R.id.search_et)
    private EditText search_et;
    @ViewInject(R.id.cancal)
    private ImageView cancal;
    @ViewInject(R.id.search_lv)
    private ListView search_lv;
    @ViewInject(R.id.saerch_emptyTip)
    private View saerch_lv_empty;
    private List<PersonalIDao.userList> kefuLs = new ArrayList<>();//记录搜索到的客服信息
    private List<SkillListDao.SkillList> groupLs = new ArrayList<>(); //记录搜索到的群组信息
    private List<Map<String, String>> hYLs = new ArrayList<>();//记录搜索到的会员信息
    private List<ServexDao.Info> servexLs = new ArrayList<>();//记录搜索到的服务号信息
    /*** 搜索数据listView条目点击监听*/
    AdapterView.OnItemClickListener mSearchAdapterItemOnClikListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            if (position == 0 || position == kefuLs.size() + 1 || position == kefuLs.size() + groupLs.size() + 2 || position == hYLs.size() + kefuLs.size() + groupLs.size() + 3) {
                return;
            }
            Object type = getType(position);
            if (type instanceof PersonalIDao.userList) {
                Intent intent = new Intent(getApplicationContext(), contact_view.class);
                intent.putExtra("kefuId", ((PersonalIDao.userList) type).kefuId);
                startActivity(intent);
            } else if (type instanceof SkillListDao.SkillList) {
                Intent intent = new Intent(getApplicationContext(), group_view.class);
                intent.putExtra("skillId", ((SkillListDao.SkillList) type).skillId);
                startActivity(intent);
            } else if (type instanceof ServexDao.Info) {
                Intent intent = new Intent(getApplication(), servex_view.class);
                intent.putExtra("servexId", ((ServexDao.Info) type).toString());
                startActivity(intent);
            }
        }
    };
    private SearchAdapter adapter;
    //是否请求过数据
    private boolean IsGetDateState = false;
    //显示搜索结果
    private Handler mSetSearchResult = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            } else {
                SearchAdapter adapter = new SearchAdapter();
                search_lv.setAdapter(adapter);
            }
        }
    };
    private ServexDao servexdao;
    private PersonalIDao personalI;
    private SkillListDao skillListDao;
    /*** 搜索输入框文本改变监听器*/
    private TextWatcher mSearchEtTxChangerLinstener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            String nR = charSequence.toString();
            clearDara();
            if (!TextUtils.isEmpty(nR)) {
                cancal.setVisibility(View.VISIBLE);
                addSearchResult(nR);
            } else {
                cancal.setVisibility(View.GONE);
                mSetSearchResult.sendEmptyMessage(0);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };
    private String token;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        token = SPUtils.getString(this, "token", "");
        //开启监听网络状态发生改变
        intent = new Intent(this, ListenerNetWorkChangeService.class);
        startService(intent);
        //如果有网络
        if (GetNetWorkUtil.getNetWorkState(this)) {
            IsGetDateState = true;
        } else {
            IsGetDateState = false;
        }
        WebScoket.conn(token);
        MsgTipUtils.playTip(this);
        getAllDate();
        initData();
        AllDataPull();
    }

    @Override
    public int getResoultLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        ViewUtils.inject(main.this);//增加注解
        initUI();
    }

    @Override
    public void initListener() {
        chat.setOnClickListener(this);
        adress.setOnClickListener(this);
        me.setOnClickListener(this);
        title_search.setOnClickListener(this);
        back.setOnClickListener(this);
        cancal.setOnClickListener(this);
        search_et.addTextChangedListener(mSearchEtTxChangerLinstener);
        search_lv.setOnItemClickListener(mSearchAdapterItemOnClikListener);
        content_Vp.setOnPageChangeListener(mMainVpScrollListener);
        WebScoket.RefactorListener(mRefatorMainMsgCountListener);
    }

    /**
     * 准备全部的数据
     */
    private void getAllDate() {
        GetAllInfoUtils.infoUtils.getInfo(constant.AllMSG + "/kefu/list", token, this, constant.KEFU);
        GetAllInfoUtils.infoUtils.getInfo(constant.AllMSG + "/skill/list", token, this, constant.SKILL);
        GetAllInfoUtils.infoUtils.getInfo(constant.AllMSG + "/member/list", token, this, constant.MEMBER);
        GetAllInfoUtils.infoUtils.getInfo(constant.AllMSG + "/tourist/list", token, this, constant.TOURIST);
        GetAllInfoUtils.infoUtils.getInfo(constant.AllMSG + "/servex/list", token, this, constant.SERVEX);
        GetAllInfoUtils.infoUtils.getInfo(constant.AllMSG + "/text/list", token, this, constant.TEXT);
        GetAllInfoUtils.infoUtils.getInfo(constant.AllMSG + "/orderprop/list", token, this, constant.ORDERPROP);
        GetAllInfoUtils.infoUtils.getInfo(constant.AllMSG + "/article/list", token, this, constant.ARTICLE);
        GetAllInfoUtils.infoUtils.getInfo(constant.AllMSG + "/filex/list", token, this, constant.FILEX);
        GetAllInfoUtils.infoUtils.getInfo(constant.AllMSG + "/gdataprop/list", token, this, constant.GDATAPROP);
    }

    /*** 准备三个Fragment*/
    public void initData() {
        homeFgList = new ArrayList<>();
        history chat = new history();
        contact adress = new contact();
        mine me = new mine();
        homeFgList.add(chat);
        homeFgList.add(adress);
        homeFgList.add(me);
        HomeFgVpAdapter adapter = new HomeFgVpAdapter(fm, homeFgList);
        content_Vp.setAdapter(adapter);
        content_Vp.setOffscreenPageLimit(2);
        Log.e("size", homeFgList.size() + "");
//        //添加第一个界面
//        FragmentTransaction transaction = fm.beginTransaction();
//        transaction.add(R.id.content_fl, homeFgList.get(0)).commit();
    }

    /*** tab栏控件初始化*/
    private void initUI() {
        search_lv.setEmptyView(saerch_lv_empty);
        ChangeIcon(true, 0);
        chat.setTabIcon(R.drawable.tab_selector_chat);
        chat.setSelected(true);
        chat.setTabText("聊天");
        chat.setMsg_count("0");
        adress.setTabIcon(R.drawable.tab_selector_adress);
        adress.setSelected(false);
        adress.setTabText("通讯录");
        adress.setMsg_count("0");
        me.setTabIcon(R.drawable.tab_selector_myself);
        me.setSelected(false);
        me.setTabText("我的");
        me.setMsg_count("0");
    }

    //解析所有搜索相关的数据
    private void AllDataPull() {
        Gson gson = new Gson();
        //服务号
        try {
            String servexData = SPUtils.getString(this, constant.SERVEX, "");
            servexdao = gson.fromJson(servexData, ServexDao.class);
            //联系人
            String ContaceData = SPUtils.getString(this, constant.KEFU, "");
            personalI = gson.fromJson(ContaceData, PersonalIDao.class);
            //群聊
            String skillList = SPUtils.getString(this, constant.SKILL, "");
            skillListDao = gson.fromJson(skillList, SkillListDao.class);
        } catch (Exception e) {
            Toast.makeText(this, "数据异常,请检查网络连接", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    //搜素结果添加
    private void addSearchResult(String searchTx) {
        //如果输入框的内容是中文
        if (searchTx.matches("[\\u4E00-\\u9FA5]+")) {
            for (int i = 0; i < servexdao.data.size(); i++) {
                String servexTitle = servexdao.data.get(i).servexTitle;
                if (servexTitle.contains(searchTx)) {
                    servexLs.add(servexdao.data.get(i));
                }
            }
            for (int i = 0; i < personalI.data.size(); i++) {
                String kefuRealname = personalI.data.get(i).kefuRealname;
                if (kefuRealname.contains(searchTx)) {
                    kefuLs.add(personalI.data.get(i));
                }
            }
            for (int i = 0; i < skillListDao.data.size(); i++) {
                String skillName = skillListDao.data.get(i).skillTitle;
                if (skillName.contains(searchTx)) {
                    groupLs.add(skillListDao.data.get(i));
                }
            }
            mSetSearchResult.sendEmptyMessage(0);
        } else {
            //字母匹配
            for (int i = 0; i < servexdao.data.size(); i++) {
                String servexTitle = servexdao.data.get(i).servexTitle;
                if (Chinese2SpellUtils.getPingYin(servexTitle, 1).contains(searchTx) || Chinese2SpellUtils.getPingYin(servexTitle, 0).contains(searchTx)) {
                    servexLs.add(servexdao.data.get(i));
                }
            }
            for (int i = 0; i < personalI.data.size(); i++) {
                String kefuRealname = personalI.data.get(i).kefuRealname;
                if (Chinese2SpellUtils.getPingYin(kefuRealname, 1).contains(searchTx) || Chinese2SpellUtils.getPingYin(kefuRealname, 0).contains(searchTx)) {
                    kefuLs.add(personalI.data.get(i));
                }
            }
            for (int i = 0; i < skillListDao.data.size(); i++) {
                String skillName = skillListDao.data.get(i).skillTitle;
                if (Chinese2SpellUtils.getPingYin(skillName, 1).contains(searchTx) || Chinese2SpellUtils.getPingYin(skillName, 0).contains(searchTx)) {
                    groupLs.add(skillListDao.data.get(i));
                }
            }
            mSetSearchResult.sendEmptyMessage(0);
        }
    }

    private void clearDara() {
        kefuLs.removeAll(kefuLs);
        groupLs.removeAll(groupLs);
        hYLs.removeAll(hYLs);
        servexLs.removeAll(servexLs);
    }

    private void setSearchIsShow(boolean state) {
        search_layout.setVisibility(state ? View.VISIBLE : View.GONE);
    }

    //改变状态
    private void ChangeIcon(boolean selected, int index) {
        for (int i = 0; i < tab_ll.getChildCount(); i++) {
            TabView childAt = (TabView) tab_ll.getChildAt(i);
            childAt.selectState(i == index ? selected : !selected);
        }
    }

    //切换
//    public void switchContent(Fragment from, Fragment to,int type) {
//        if (mContent != to) {
//            mContent = to;
//            FragmentTransaction ft = fm.beginTransaction();
//            if (!to.isAdded()) {
//                ft.hide(from).add(R.id.content_fl, to).commit();
//            } else {
//                ft.hide(from).show(to).commit();
//            }
//            ChangeIcon(true, type);
//        }
//    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.chat:
                //switchContent(getVisibleFragment(), homeFgList.get(0),0);
                content_Vp.setCurrentItem(0, false);
                ChangeIcon(true, 0);
                break;
            case R.id.adress:
                //switchContent(getVisibleFragment(), homeFgList.get(1),1);
                content_Vp.setCurrentItem(1, false);
                ChangeIcon(true, 1);
                break;
            case R.id.me:
                //switchContent(getVisibleFragment(), homeFgList.get(2),2);
                content_Vp.setCurrentItem(2, false);
                ChangeIcon(true, 2);
                break;
            case R.id.title_search:
                setSearchIsShow(true);
                break;
            case R.id.back:
                search_et.setText("");
                setSearchIsShow(false);
                break;
            case R.id.cancal:
                search_et.setText("");
                break;
        }
    }
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if(search_layout.getVisibility()==View.VISIBLE)
//            {
//                search_et.setText("");
//                setSearchIsShow(false);
//            }
//            else{
//              moveTaskToBack(false);
//            }
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    @Override
    public void onBackPressed() {
        if (search_layout.getVisibility() == View.VISIBLE) {
            search_et.setText("");
            setSearchIsShow(false);
            return;
        }
        super.onBackPressed();
    }

    //    public void onBackPressed() {
//        Intent setIntent = new Intent(Intent.ACTION_MAIN);
//        setIntent.addCategory(Intent.CATEGORY_HOME);
//        setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startActivity(setIntent);
//    }
//    public Fragment getVisibleFragment() {
//        List<Fragment> fragments = fm.getFragments();
//        for (Fragment fragment : fragments) {
//            if (fragment != null && fragment.isVisible()) {
//                return fragment;
//            }
//        }
//        return null;
//    }
    private Object getType(int i) {
        if (i > 0 && i < kefuLs.size() + 1) {
            return kefuLs.get(i - 1);
        } else if (i > kefuLs.size() + 1 && i < (kefuLs.size() + groupLs.size()) + 2) {
            return groupLs.get(i - kefuLs.size() - 2);
        } else if (i > kefuLs.size() + groupLs.size() + 2 && i < (kefuLs.size() + groupLs.size() + hYLs.size()) + 3) {
            return hYLs.get(i - kefuLs.size() - groupLs.size() - 3);
        } else if (i > kefuLs.size() + groupLs.size() + hYLs.size() + 3 && i < kefuLs.size() + groupLs.size() + hYLs.size() + servexLs.size() + 4) {
            return servexLs.get(i - kefuLs.size() - groupLs.size() - hYLs.size() - 4);
        }
        return null;
    }

    /**
     * 获取消息未读总数
     */
    public void initHistoryDR() {
        String data = ChatRecordSPUtils.getRecordString(this, constant.HISTROYCHATPEOPLE, constant.HISTROYCHATPEOPLE, "").trim();
        int DRCount = 0;
        if (!data.equals("")) {
            String[] split = data.split(",");
            for (int i = 0; i < split.length; i++) {
                String count = ChatRecordSPUtils.getRecordString(this, split[i], split[i] + "_count", "0");
                DRCount += Integer.parseInt(count);
            }
            chat.setMsg_count(DRCount + "");
        } else {
            chat.setMsg_count("0");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initHistoryDR();
    }

    @Override
    public void NetState(int state) {
        if (homeFgList != null) {
            history fragment = (history) homeFgList.get(0);
            fragment.showNoNetWorkTip(state);
        }
        if (state == NetUtils.MOBILE || state == NetUtils.WIFINET) {
            if (!WebScoket.WebScoketConnected) {
                if (!WebScoket.WebScoketConnected) {
                    WebScoket.conn(token);
                }
            }
        } else {
            Toast.makeText(this, "连接不到服务器，检查您的网络是否已经开启", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(intent);
    }

    //搜索结果的适配器
    class SearchAdapter extends BaseAdapter {
        BitmapUtils utils;

        public SearchAdapter() {
            utils = new BitmapUtils(getApplicationContext());
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0 || position == kefuLs.size() + 1 || position == kefuLs.size() + groupLs.size() + 2 || position == hYLs.size() + kefuLs.size() + groupLs.size() + 3) {
                return 0;
            }
            return 1;
        }

        @Override
        public int getCount() {
            if (kefuLs.size() + groupLs.size() + hYLs.size() + servexLs.size() == 0) {
                return 0;
            }
            return kefuLs.size() + groupLs.size() + hYLs.size() + servexLs.size() + 4;
        }

        @Override
        public Object getItem(int i) {
            return getType(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            switch (getItemViewType(i)) {
                case 0:
                    if (view == null) {
                        view = View.inflate(getApplicationContext(), R.layout.search_list_tip, null);
                    }
                    TextView tv = (TextView) view.findViewById(R.id.searchResult_tip);
                    if (i == 0) {
                        tv.setText("联系人");
                    } else if (i == kefuLs.size() + 1) {
                        tv.setText("群聊");
                    } else if (i == kefuLs.size() + groupLs.size() + 2) {
                        tv.setText("会员");
                    } else {
                        tv.setText("服务号");
                    }
                    return view;
                case 1:
                    ImageView viewById = null;
                    TextView name = null;
                    if (view == null) {
                        view = View.inflate(getApplicationContext(), R.layout.search_list_item, null);
                    }
                    viewById = view.findViewById(R.id.head_portrait);
                    name = view.findViewById(R.id.name);
                    Object type = getType(i);
                    if (type instanceof PersonalIDao.userList) {
                        utils.display(viewById, ((PersonalIDao.userList) type).kefuAvatar);
                        name.setText(((PersonalIDao.userList) type).kefuRealname);
                    } else if (type instanceof SkillListDao.SkillList) {
                        viewById.setImageResource(R.drawable.group_icon);
                        name.setText(((SkillListDao.SkillList) type).skillTitle);
                    } else if (type instanceof ServexDao.Info) {
                        utils.display(viewById, ((ServexDao.Info) type).servexAvatar);
                        name.setText(((ServexDao.Info) type).servexTitle);
                    }
                    return view;
                default:
                    return null;
            }
        }
    }
}
